package com.aneliya.validator.component;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.SwingUtilities;
import javax.swing.text.JTextComponent;

import com.aneliya.validator.Validator;
import com.aneliya.validator.data.IDataValidator;

public class TextComponentValidator extends Validator {
	protected JTextComponent component;
	protected IDataValidator dataValidator;
	
	public Boolean isValid() {
		return dataValidator.isValid(component.getText());
	}
	
	public TextComponentValidator(
			JTextComponent component, 
			IDataValidator dataValidator) {
		super();
		this.component = component;
		this.dataValidator = dataValidator;
		
		initializeComponentChangeListeners();
	}

	protected void initializeComponentChangeListeners() {
		KeyListener listener = new KeyListener() {
			public void keyTyped(KeyEvent e) {
				SwingUtilities.invokeLater(new Runnable() {
					public void run() {
						dispatchValidatorChanged();
					}
				});
			}
			
			public void keyPressed(KeyEvent e) {
			}
			public void keyReleased(KeyEvent e) {
			}
		};
		component.addKeyListener(listener);
	}
	
}
